package com.example.smartvillage;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavInflater;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import cn.bmob.v3.Bmob;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "-----主活动-----";
    public static String APPID = "6fe8eb567bb46bfa61a97578a8e41206";
    private static final int REQUEST_CODE_SCAN = 111;

    MaterialToolbar toolbar;
    BottomNavigationView bottomNav;
    FragmentManager fragmentManager;
    NavController navController;
    ImageView code_scan;
    AutoCompleteTextView searchBar;

    ActivityResultLauncher<String> requestCameraPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                } else {
                    new AlertDialog.Builder(this)
                            .setTitle("缺少相机权限")
                            .setMessage("需要相机权限以使用扫码功能")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            })
                            .show();
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "onCreate: ");

        //获取FragmentManager与NavController
        fragmentManager = getSupportFragmentManager();
        NavHostFragment navHostFragment = (NavHostFragment) fragmentManager
                .findFragmentById(R.id.nav_host_fragment);
        navController = navHostFragment.getNavController();//获取导航控制器

        NavInflater inflater = navHostFragment.getNavController().getNavInflater();
        NavGraph graph = navController.getGraph();
        Log.d(TAG, "StartDestination: "+graph.getStartDestination());
        graph.setStartDestination(R.id.homeFragment);
        Log.d(TAG, "StartDestination: "+graph.getStartDestination());

        //初始化底部导航栏
        bottomNav = findViewById(R.id.bottom_nav);
        NavigationUI.setupWithNavController(bottomNav, navController);//将底部导航栏与导航控制器绑定

        //初始化工具栏
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);//将工具栏设置为ActionBar
        getSupportActionBar().setDisplayShowTitleEnabled(false);//隐藏工具栏上的默认应用名

        //扫码
        code_scan = toolbar.findViewById(R.id.code_scan);
        code_scan.setOnClickListener(onCodeScanClickListener);

        //初始化搜索框
        searchBar = toolbar.findViewById(R.id.search_bar);
        searchBar.setOnFocusChangeListener(onSearchBarFocusChangeListener);//设置监听器

        //启动bmob
        Bmob.initialize(this,APPID);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                new AlertDialog.Builder(this)
                        .setTitle("结果")
                        .setMessage(content)
                        .setPositiveButton("确定", (dialog, which) -> dialog.cancel())
                        .show();
            }
        }
    }

    //点击搜索框时跳转
    View.OnFocusChangeListener onSearchBarFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus) {
                navController.navigate(R.id.searchFragment);
            }
        }
    };

    //扫码按钮响应
    View.OnClickListener onCodeScanClickListener = v -> {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SCAN);
        }
        else {
            requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA);
        }
    };
}